<template>
  <div class="scheduled-tasks">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">定时识别管理</h1>
        <p class="page-description">Cron 表达式其实就是一种 定时闹钟规则，用来告诉系统在什么时间点执行任务。它的格式依次表示“秒、分、时、日、月、周、年”，就像日历加闹钟的组合。例如：每天早上 9 点执行（0 0 9 * * ?）、每周一早上 7 点执行（0 0 7 ? * 2）、每月 1 号早上 6 点执行（0 0 6 1 * ?）。理解起来可以把它看作“什么时候要干活”的设定：选好日期和时间，系统就会在那个时刻自动执行任务。</p>
      </div>
      <el-button type="primary" @click="showCreateDialog = true">
        新建任务
      </el-button>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索任务名称或描述"
          :prefix-icon="Search"
          @keyup.enter="handleSearch"
          clearable
        />
      </div>
      <div class="filter-bar">
        <el-select
          v-model="statusFilter"
          placeholder="任务状态"
          clearable
        >
          <el-option
            v-for="dict in sys_job_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </div>
      <el-button type="primary" @click="handleSearch">
        搜索  
      </el-button>
    </div>

    <!-- 任务列表 -->
    <div class="tasks-table">
      <el-table
        :data="filteredTasks"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="jobName" label="任务名称" width="200" />
        <el-table-column prop="jobGroup" label="任务组" width="120" />
        <el-table-column prop="cronExpression" label="Cron表达式" width="150" />
        <el-table-column prop="status" label="任务状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.status === '0' ? 'success' : 'danger'"
              size="small"
            >
              {{ row.status === '0' ? '正常' : '暂停' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="nextValidTime" label="下次执行时间" width="180" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="editTask(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="row.status === '1'"
              type="success"
              size="small"
              @click="startTask(row)"
            >
              启动
            </el-button>
            <el-button
              v-else
              type="warning"
              size="small"
              @click="pauseTask(row)"
            >
              暂停
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteTask(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 创建/编辑任务对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="isEdit ? '编辑任务' : '新建任务'"
      width="800px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="taskFormRef"
        :model="taskForm"
        :rules="taskRules"
        label-width="120px"
      >
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="taskForm.jobName" placeholder="请输入任务名称" />
        </el-form-item>
        
        <el-form-item label="任务组" prop="jobGroup">
          <el-select v-model="taskForm.jobGroup" placeholder="请选择任务组">
            <el-option
              v-for="dict in sys_job_group"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="调用目标" prop="invokeTarget">
          <el-input
            v-model="taskForm.invokeTarget"
            placeholder="请输入调用目标字符串"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="Cron表达式" prop="cronExpression">
          <div class="cron-input-group">
            <el-input
              v-model="taskForm.cronExpression"
              placeholder="请输入Cron表达式"
              style="flex: 1; margin-right: 10px;"
            />
            <el-button @click="showCronDialog = true">生成表达式</el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="执行策略" prop="misfirePolicy">
          <el-radio-group v-model="taskForm.misfirePolicy">
            <el-radio label="1">立即执行</el-radio>
            <el-radio label="2">执行一次</el-radio>
            <el-radio label="3">放弃执行</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="是否并发" prop="concurrent">
          <el-radio-group v-model="taskForm.concurrent">
            <el-radio label="0">允许</el-radio>
            <el-radio label="1">禁止</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="任务状态" prop="status">
          <el-radio-group v-model="taskForm.status">
            <el-radio label="0">暂停</el-radio>
            <el-radio label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="taskForm.remark"
            placeholder="请输入备注信息"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="submitTask" :loading="submitting">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Cron表达式生成器对话框 -->
    <el-dialog
      v-model="showCronDialog"
      title="Cron表达式生成器"
      width="900px"
    >
      <Crontab
        @hide="showCronDialog = false"
        @fill="fillCronExpression"
        :expression="taskForm.cronExpression"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import Crontab from '@/components/Crontab/index.vue'
import { 
  listCustomerJob, 
  getCustomerJob, 
  createHttpTask, 
  updateCustomerJob, 
  delCustomerJob, 
  changeCustomerJobStatus, 
  runCustomerJob 
} from '@/api/agriculture/xctl/job'

// 获取全局属性
const { proxy } = getCurrentInstance()
const { sys_job_status, sys_job_group, sys_job_policy } = proxy.useDict('sys_job_status', 'sys_job_group', 'sys_job_policy')

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const showCreateDialog = ref(false)
const showCronDialog = ref(false)
const isEdit = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const taskFormRef = ref()

// 任务列表数据
const tasks = ref([])

// 任务表单数据
const taskForm = reactive({
  jobId: null,
  jobName: '',
  jobGroup: 'DEFAULT',
  cronExpression: '',
  invokeTarget: '',
  misfirePolicy: '1',
  concurrent: '1',
  status: '1',
  remark: ''
})

// 表单验证规则
const taskRules = {
  jobName: [
    { required: true, message: '请输入任务名称', trigger: 'blur' }
  ],
  jobGroup: [
    { required: true, message: '请输入任务组', trigger: 'blur' }
  ],
  cronExpression: [
    { required: true, message: '请输入Cron表达式', trigger: 'blur' }
  ],
  invokeTarget: [
    { required: true, message: '请输入调用目标', trigger: 'blur' }
  ]
}

// 计算属性
const filteredTasks = computed(() => {
  let result = tasks.value
  
  // 按搜索关键词过滤
  if (searchQuery.value) {
    result = result.filter(task => 
      task.jobName.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      task.remark.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }
  
  // 按状态过滤
  if (statusFilter.value) {
    result = result.filter(task => task.status === statusFilter.value)
  }
  
  return result
})

// 方法

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadTasks()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadTasks()
}

const loadTasks = async () => {
  loading.value = true
  try {
    const response = await listCustomerJob({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      jobName: searchQuery.value,
      status: statusFilter.value
    })
    tasks.value = response.rows || []
    total.value = response.total || 0
  } catch (error) {
    ElMessage.error('加载任务列表失败')
    tasks.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const editTask = (task) => {
  isEdit.value = true
  Object.assign(taskForm, task)
  showCreateDialog.value = true
}

const startTask = async (task) => {
  try {
    await changeCustomerJobStatus(task.jobId, '0')
    task.status = '0'
    ElMessage.success('任务启动成功')
    await loadTasks()
  } catch (error) {
    ElMessage.error('任务启动失败')
  }
}

const pauseTask = async (task) => {
  try {
    await changeCustomerJobStatus(task.jobId, '1')
    task.status = '1'
    ElMessage.success('任务暂停成功')
    await loadTasks()
  } catch (error) {
    ElMessage.error('任务暂停失败')
  }
}

const deleteTask = async (task) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除任务 "${task.jobName || task.taskName}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await delCustomerJob(task.jobId)
    ElMessage.success('任务删除成功')
    await loadTasks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('任务删除失败')
    }
  }
}

const handleDialogClose = () => {
  showCreateDialog.value = false
  isEdit.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(taskForm, {
    jobId: null,
    jobName: '',
    jobGroup: 'DEFAULT',
    cronExpression: '',
    invokeTarget: '',
    misfirePolicy: '1',
    concurrent: '1',
    status: '1',
    remark: ''
  })
  if (taskFormRef.value) {
    taskFormRef.value.clearValidate()
  }
}

const submitTask = async () => {
  if (!taskFormRef.value) return
  
  try {
    await taskFormRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      // 更新任务
      await updateCustomerJob(taskForm)
      ElMessage.success('任务更新成功')
    } else {
      // 创建任务
      const createData = {
        taskName: taskForm.jobName,
        apiUrl: taskForm.invokeTarget,
        cronExpression: taskForm.cronExpression,
        remark: taskForm.remark
      }
      await createHttpTask(createData)
      ElMessage.success('任务创建成功')
    }
    
    await loadTasks()
    
    handleDialogClose()
  } catch (error) {
    if (error !== false) {
      ElMessage.error(isEdit.value ? '任务更新失败' : '任务创建失败')
    }
  } finally {
    submitting.value = false
  }
}

const fillCronExpression = (expression) => {
  taskForm.cronExpression = expression
  showCronDialog.value = false
}

// 组件挂载时加载数据
onMounted(() => {
  loadTasks()
})
</script>

<style scoped>
.scheduled-tasks {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1a202c;
  margin: 0 0 8px 0;
}

.page-description {
  color: #6b7280;
  margin: 0;
  font-size: 14px;
}



.search-section {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-bar {
  flex: 1;
  max-width: 400px;
}

.filter-bar {
  width: 200px;
}

.tasks-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 24px;
}

.pagination {
  display: flex;
  justify-content: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.cron-input-group {
  display: flex;
  align-items: center;
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* Element Plus 样式覆盖 */
:deep(.el-table) {
  border: none;
}

:deep(.el-table th) {
  background-color: #f8fafc;
  color: #374151;
  font-weight: 600;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f1f5f9;
}

:deep(.el-table tr:hover > td) {
  background-color: #f8fafc;
}

:deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #f1f5f9;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  border-top: 1px solid #f1f5f9;
}
</style>